#!/usr/bin/python3

import threading
import os
from dataPath import resultdirBasepath,searchRecordspath
from dboperation import save_midwordkeys
from stopWordDic import inStopwordDic

class midwordkeysThread (threading.Thread):
    
    def __init__(self, threadID, name,  SeedKeyword, fencilog, optimization):
        self.midwordkeysdic ={}
        #这个是搜索记录的次数
        self.num_seedkeys = 0
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.SeedKeyword=SeedKeyword
        self.fencilog = fencilog
        self.optimization = optimization
        
    def run(self):
        print ("开始线程：" + self.name + "并处理---" + self.SeedKeyword + "---关键字")
        if(not self.optimization):
            for  i in self.fencilog:
                i = i.decode('utf-8')
                if self.SeedKeyword in i:
                    #这个是如果种子关键字在这一行，就将该行所有数据当作中介保存,
                    self.num_seedkeys +=1
                    str = i.split()
                    for word in str:
                        #不和种子关键字相同,不在停词表中
                        if word !=self.SeedKeyword and (not inStopwordDic(word)) :
                            if self.SeedKeyword not in word:
                                self.midwordkeysdic[word] = self.midwordkeysdic.get(word, 0) + 1  
                            else:
                                newMidKey = word.strip(self.SeedKeyword)
                                self.midwordkeysdic[newMidKey] = self.midwordkeysdic.get(newMidKey, 0) + 1     
        else:
            #偶数行是词语，奇数行是词性
            for index,sentence in enumerate(self.fencilog):
                if index%2 == 1:
                    sentence = sentence.decode('UTF-8')
                    if self.SeedKeyword in sentence:
                        #这个是如果种子关键字在这一行，就将该行所有数据当作中介保存
                        self.num_seedkeys +=1
                        str = sentence.split()
                        for word in str:
                                #不和种子关键字相同,不在停词表中
                                if word !=self.SeedKeyword and (not inStopwordDic(word)):
                                    if self.SeedKeyword not in word:
                                        self.midwordkeysdic[word] = self.midwordkeysdic.get(word, 0) + 1  
                                    else:
                                        newMidKey = word.strip(self.SeedKeyword)
                                        self.midwordkeysdic[newMidKey] = self.midwordkeysdic.get(newMidKey, 0) + 1    
                    
        print("已经找到所有与种子关键字---"+self.SeedKeyword+"---有关的中介关键字，下面开始把结果写入文件并退出线程：" + self.name)
        #创建文件夹
        self.creatDir(self.SeedKeyword)
        #将中介关键词排序并存入进文件夹
        self.outputMidKeyWithStopDic(self.SeedKeyword)
        #存人数据库
        midwordkeylist = []
        list = dict(sorted(self.midwordkeysdic.items(), key=lambda x: x[1], reverse=True)).items()
        count = 0
        for key, value in list:
            if count >= 10:
                break
            tempdic={}
            tempdic[key] =value
            midwordkeylist.append(tempdic)
            count += 1
            pass
        print(midwordkeylist)
        save_midwordkeys(self.SeedKeyword, midwordkeylist)
        
    
    def creatDir(self, keyWord):
        if not os.path.exists(resultdirBasepath + keyWord):
            os.makedirs(resultdirBasepath + keyWord)


    def outputMidKeyWithStopDic(self, keyWord):
            midkeyfile = open(resultdirBasepath + keyWord + "\\MidKey.txt", 'w', encoding='utf-8')
            list = dict(sorted(self.midwordkeysdic.items(), key=lambda x: x[1], reverse=True)).items()
            for key, value in list:
                midkeyfile.write(key +" "+str(value)+'\n')
                pass
            print("--" + keyWord + "--中介关键词结果已完成写入")
            midkeyfile.close()
    

   

